package cn.com.elite;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;

import com.elite.algorithm.GUID;

import cn.com.elite.Util;

public class EliteRecordFtpService1 extends HttpServlet{
	private static final Log log=LogFactory.getLog(EliteRecordFtpService1.class);
	private static Map ip_username_map;
	private static Map username_password_map;
	private static Map username_port_map;
	private static String ContentType;
	private static String ContextPath="";
	private static String CMDcommand="";
	
	
	public void init(){
		ContextPath=this.getInitParameter("ContextPath");
		log.info("ContextPath:"+ContextPath);
		CMDcommand=this.getInitParameter("CMDcommand");
		log.info("CMDcommand:"+CMDcommand);
		try{
			InputStream inputStream=EliteRecordFtpService.class.getResourceAsStream("eliteftp.properties"); 
			Properties p=new Properties();   
			p.load(inputStream); 
			String count=p.getProperty("COUNT");
			ContentType=p.getProperty("ContentType");
			log.info("init_count:"+count);
			int num=Integer.parseInt(count);
			log.info("init_num:"+num);
			ip_username_map=new HashMap();
			username_password_map=new HashMap();
			username_port_map=new HashMap();
			for(int i=1;i<num+1;i++){
				String ip=p.getProperty("IP"+i);
				String username=p.getProperty("USERNAME"+i);
				String password=p.getProperty("PASSWORD"+i);
				String port=p.getProperty("PORT"+i);
				log.info("ip:"+ip);
				log.info("username:"+username);
				log.info("password:"+password);
				log.info("port:"+port);
				ip_username_map.put(ip,username);
				username_password_map.put(username,password);
				username_port_map.put(username,Integer.parseInt(port));
			}
			log.info("服务初始化读取配置文件完成");
		}catch(Exception e){
			log.error("服务初始化读取配置文件错误");
			log.error(Util.getERRO(e));
		}
	}
	public static void main(String[] args){
		String a="192.168.162.203/1/0/20130723/102/1028432.V3";
		a=a.replaceAll(".*?((\\d{0,3}\\.){3}\\d{0,3}).*","$1");
		System.out.println(a);
	}
	private String getip(String FtpURL) throws Exception{
		String ip=FtpURL;
		ip=ip.replaceAll(".*?((\\d{0,3}\\.){3}\\d{0,3}).*","$1");
		return ip;	
	}
	private String getfileName(String FtpURL) throws Exception{
		String fileName="";
		String FtpURL1=FtpURL.replace("//","");
		fileName=FtpURL1.substring(FtpURL1.indexOf("/"),FtpURL1.length());
		return fileName;
	}
	private String getfileName1(String FtpURL) throws Exception{
		String fileName="";
		fileName=FtpURL.substring(FtpURL.lastIndexOf("/")+1,FtpURL.length());
		return fileName;
	}
	private FTPClient GetFtp(String host,int port,String username,String password){
		FTPClient ftp=new FTPClient();
		try{
			ftp.connect(host, port); 			
			ftp.login(username, password);
			return ftp;
		}catch(Exception e){
			log.error("FTP获取失败");
			log.error(Util.getERRO(e));
			return null;
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException{
		doPost(request,response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException{
		String FtpURL=Util.filter(request.getParameter("FtpURL"));
		log.info("FtpURL:"+FtpURL);
		String Fileformat=Util.filter(request.getParameter("Fileformat"));
		log.info("Fileformat:"+Fileformat);
		FTPClient ftp=null;
		String fileName1="";
		String filename_temp="";
		String file_temp1="";
		String file_temp="";
		response.setHeader("Cache-Control","no-cache");
		response.setHeader("pragma","no-cache");
		try{
			fileName1=getfileName1(FtpURL);
			log.info("doGet_fileName1:"+fileName1);
			String fileName=getfileName(FtpURL);
			log.info("doGet_fileName:"+fileName);
			String ip=getip(FtpURL);
			log.info("doGet_ip:"+ip);
			String username=Util.filter((String)ip_username_map.get(ip));
			log.info("doGet_username:"+username);
			String password=Util.filter((String)username_password_map.get(username));
			log.info("doGet_password:"+password);
			int port=(Integer)username_port_map.get(username);
			log.info("doGet_port:"+port);
			ftp=GetFtp(ip,port,username,password);



			log.info("doGet_fileName1:"+fileName1);
			log.info("doGet_fileName:"+fileName);
			ftp=GetFtp(ip,port,username,password);
			response.setContentType("audio/x-wav;utf-8");
			response.setHeader("Content-disposition","inline;filename="+fileName1);
			GUID guid=new GUID();
			file_temp1=ContextPath+"/"+fileName1;
			log.debug("file_temp1:"+file_temp1);
				
			String address=this.getServletContext().getRealPath("/");
			filename_temp="temp\\"+guid.toString()+".wav";
			log.debug("address:"+address);
			file_temp=address+filename_temp;		
		
			log.debug("file_temp:"+file_temp);
			File file=new File(file_temp1);
			FileOutputStream fos=new FileOutputStream(file);
			boolean flag=ftp.retrieveFile(fileName, fos);
			log.debug("flag:"+flag);
			fos.flush();
			fos.close();

			String command=CMDcommand+" "+file_temp1+" "+file_temp+" "+getCMDformat(Integer.parseInt(Fileformat));
			log.debug("command:"+command);
			Process process=Runtime.getRuntime().exec(command);
	        int exitcode=process.waitFor();
	        log.debug("exitcode:"+exitcode);
	        if(exitcode==0||exitcode==1){
	        	log.debug("convert successfully");
	        }else{
	             log.debug("convert failed and return "+exitcode);
	        }
	        process.getInputStream().close();
	        process.getOutputStream().close();
	        process.getErrorStream().close();			
		}catch(Exception e){
			log.error("doGet过程错误");
			log.error(Util.getERRO(e));	
		}finally{
			ftp.disconnect();
			response.sendRedirect(filename_temp); 
			log.info("返回完成,FTP关闭");
		}
	}

	private String getCMDformat(int fileformat){ 
		log.debug("fileformat:"+fileformat);
		if(fileformat==11){
			return "g726_16 alawwav";			
		}else if(fileformat==1){
			return "alaw alawwav";		
		}else if(fileformat==2){
			return "ulaw ulawwav";		
		}else if(fileformat==12){
			return "dialogic6k wav";
		}else{
			return null;
		}
	}
}
